﻿//用到的命名空间 
using System;
using System.Web;

namespace msBsc.Cls
{ 
    //继承自IHttpModule接口 
    public class pageResourceGet  
    {
        //public void ProcessRequest(HttpContext context)
        //{
        //    //context.Response.Write("Hello World");
        //    doHandler(context);
        //}

        //public bool IsReusable
        //{
        //    get
        //    {
        //        return false;
        //    }
        //}

        public static void doRequest(HttpContext context)
        {
            //context.Response.Clear();
            //context.Response.ClearHeaders();
            string requestPath = context.Request.RawUrl.ToLower();
            if (!requestPath.StartsWith("/??"))
            {
                return;
            }
            requestPath = requestPath.Substring(3);
            if(requestPath.IndexOf("?")!=-1)
            {
                requestPath=requestPath.Substring(0,requestPath.IndexOf("?"));
            }
            //requestPath = requestPath + "?rm=" + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.ServerVersion;

            string strMd5PathV = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemResFileVDir + msBsc.AppLogic.Cfg.DesCry.Md5Encrypt(requestPath + msBsc.AppLogic.Cfg.SystemSet.oSystemSet.ServerVersion+"-01");
            requestPath=requestPath.TrimEnd(',',' ');
            if (requestPath.LastIndexOf(".") != -1)
            {
                strMd5PathV = strMd5PathV + requestPath.Substring(requestPath.LastIndexOf("."));
            }
            else
            {
                return;
            }

            string strMd5path = context.Server.MapPath(strMd5PathV);

            if (System.IO.File.Exists(strMd5path))
            {
                context.RewritePath(strMd5PathV);
                return;
            }
            else if (!System.IO.Directory.Exists(strMd5path))
            { 
                System.IO.Directory.CreateDirectory(new System.IO.FileInfo(strMd5path).Directory.FullName);
            }


            System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
            string[] arrstrteem = requestPath.Split(',');
            int icount = arrstrteem.Length;
            bool blResp = false;
            for (int i = 0; i < arrstrteem.Length; i++)
            {
                string strfilepath = arrstrteem[i].ToLower();
                int item33 = strfilepath.IndexOf(".js");
                if (item33 != -1)
                {
                    strfilepath = strfilepath.Substring(0, item33 + 3);
                }
                else
                {
                    item33 = strfilepath.IndexOf(".css");
                    if (item33 != -1)
                    {
                        strfilepath = strfilepath.Substring(0, item33 + 4);
                    }
                }
                if (strfilepath.EndsWith(".js"))
                {
                    if (!blResp)
                    {
                        context.Response.AddHeader("Content-type", "text/javascript;charset=gb2312");
                        blResp = true;
                    }
                }
                else if (strfilepath.EndsWith(".css"))
                {
                    if (!blResp)
                    {
                        context.Response.ContentType = "text/css";
                        context.Response.AddHeader("Content-type", "text/css");
                        blResp = true;
                    }
                }
                else
                {
                    continue;
                }

                strfilepath = strfilepath.Replace("/", "\\");
                if (!strfilepath.ToLower().StartsWith("jqplugin") && !strfilepath.ToLower().StartsWith("themes"))
                {
                    strfilepath = "jqPlugin\\" + strfilepath;
                }
                strfilepath = CurrAppPath + strfilepath;

                System.IO.FileInfo ofinfo = new System.IO.FileInfo(strfilepath);
                if (!ofinfo.Exists)
                {
                    //string sterrrr = arrstrteem[i];
                    //if (!sterrrr.StartsWith("http"))
                    //{
                    //    sterrrr = "http://g.tbcdn.cn/" + sterrrr;
                    //}

                    //msBsc.SvRef.SRWebClient oSRWebClient = new SvRef.SRWebClient();
                    //oSRWebClient.DownloadFile(sterrrr, strfilepath, false);
                    //System.IO.FileInfo ofinfo2 = new System.IO.FileInfo(strfilepath);
                    //if (!ofinfo2.Exists)
                    //{
                    continue;
                    //}
                }


                //using (System.IO.StreamReader sr = new System.IO.StreamReader(ofinfo.FullName))
                //{
                //    sbRet.AppendLine(sr.ReadToEnd());
                //}
                if (strfilepath.EndsWith(".js"))
                {
                    msBsc.AppLogic.Cfg.JSCompress oJSCompress = new AppLogic.Cfg.JSCompress();
                    sbRet.AppendLine(oJSCompress.doCompressFromFile(strfilepath));
                }
                else
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(ofinfo.FullName))
                    {
                        sbRet.AppendLine(sr.ReadToEnd());
                    }
                }
            }

            if (sbRet.Length > 0)
            {
                try
                {
                    using (System.IO.FileStream fs = new System.IO.FileStream(strMd5path, System.IO.FileMode.Create))
                    {
                        //byte[] bttm1 = System.Text.Encoding.UTF8.GetBytes(sbRet.ToString());
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.GetEncoding("UTF-8")))
                        {
                            sw.WriteLine(sbRet);    // 输出信息。
                            sw.Close(); // 关闭数据流并释放所占资源
                        }
                        fs.Close(); // 关闭并释放资源，
                        //System.IO.StreamWriter _streamWriter = new System.IO.StreamWriter(fs);
                        //using (System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(sbRet.ToString())))
                        //{
                        //    //fs.Write(
                        //}
                        //fs.Write(bttm1, 0, bttm1.Length);
                        //fs.Close();
                    }
                    context.RewritePath(strMd5PathV);
                    return;
                }
                catch { }
            }

            context.Response.Write(sbRet.ToString());
        }


        //public string MergeResourceAndCompress(string strquery)
        //{
        //    System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
        //    string[] arrstrteem = strquery.Split(',');
        //    int icount = arrstrteem.Length;
        //    for (int i = 0; i < arrstrteem.Length; i++)
        //    {
        //        string strfilepath = arrstrteem[i];
        //        //if (strfilepath.StartsWith("j_"))
        //        //{
        //        strfilepath = CurrAppPath + "jqPlugin\\" + strfilepath.Replace("/", "\\");
        //        //}
        //        msBsc.AppLogic.Cfg.JSCompress oJSCompress = new AppLogic.Cfg.JSCompress();
        //        sbRet.AppendLine(oJSCompress.doCompressFromFile(strfilepath));
        //    }

        //    return sbRet.ToString();
        //}


        private static string _CurrAppPath = "";
        /// <summary>
        /// 程序主目录,WEB站点目录，以\\结尾
        /// </summary>
        public static string CurrAppPath
        {
            get
            {
                if (_CurrAppPath == string.Empty)
                {
                    if (HttpContext.Current == null)
                    {
                        _CurrAppPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    }
                    else
                    {
                        _CurrAppPath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
                    }
                    if (!_CurrAppPath.EndsWith("\\"))
                    {
                        _CurrAppPath = _CurrAppPath + "\\";
                    }
                }
                return _CurrAppPath;
            }
        }



    }
}